package com.asion.vmovie.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.asion.vmovie.R;
import com.asion.vmovie.activities.VideoActivity;
import com.asion.vmovie.activities.WebActivity;
import com.asion.vmovie.adapters.HeaderViewPagerAdapter;
import com.asion.vmovie.adapters.NewsViewAdapter;
import com.asion.vmovie.beans.DetialsBean;
import com.asion.vmovie.beans.LunBoBean;
import com.asion.vmovie.ui.MVPContract.NewsContract;
import com.asion.vmovie.ui.MVPModel.NewsModel;
import com.asion.vmovie.ui.MVPPresenter.NewsPresenter;
import com.asion.vmovie.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;

import static com.asion.vmovie.app.MyApp.context;

/**
 * Created by asion on 16-10-17.
 */

public class NewsFragment extends BaseFragment<NewsPresenter,NewsModel> implements NewsContract.View,SwipeRefreshLayout.OnRefreshListener, ViewPager.OnPageChangeListener,Handler.Callback, HeaderViewPagerAdapter.OnImageViewClickListener, NewsViewAdapter.OnItemClickListener {

    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.refreshlayout)
    SwipeRefreshLayout refreshlayout;
    private NewsViewAdapter newsViewAdapter;
    private View view;
    private ViewPager header_viewpager;
    private LinearLayout header_linear;
    private Handler handler = new Handler(this);
    private ImageView point;
    private int page = 0;
    private HeaderViewPagerAdapter adapter;

    public static NewsFragment newInstance(){
        return new NewsFragment();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.recycler_fragment;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this,mModel);
        mPresenter.getBanner();
    }

    @Override
    protected void initView() {
        startProgressDialog();
        refreshlayout.setColorSchemeColors(Color.BLUE,Color.CYAN,Color.GRAY);
        newsViewAdapter = new NewsViewAdapter(getContext());
        recycler.setItemAnimator(new DefaultItemAnimator());
        recycler.setLayoutManager(new LinearLayoutManager(getContext()));
        recycler.setAdapter(newsViewAdapter);
        refreshlayout.setOnRefreshListener(this);

        view = LayoutInflater.from(getContext()).inflate(R.layout.home_header, null);
        newsViewAdapter.setmHeaderView(view);

        header_viewpager = ((ViewPager) view.findViewById(R.id.header_viewpager));
        header_linear = ((LinearLayout) view.findViewById(R.id.header_cricle));
        point = ((ImageView) view.findViewById(R.id.header_point));

        header_viewpager.addOnPageChangeListener(this);

        newsViewAdapter.setOnItemClickListener(this);

        recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if(dy > 0){
                    EventBus.getDefault().post("hide");
                }else{
                    EventBus.getDefault().post("show");
                }
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int itemCount = layoutManager.getItemCount();
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (!loading&&itemCount<(lastVisibleItemPosition+4)) {
                    mPresenter.getNewsData(++page,10);
                    loading=true;
                }
            }
        });
    }

    private boolean loading = false;
    @Override
    public void onRefresh() {
        page=0;
        newsViewAdapter.removeAll();
        new Handler().postDelayed(()->refreshlayout.setRefreshing(false),3000);
    }

    @Override
    public void showDataSuccess(Object o) {
        if(o instanceof LunBoBean){
            for (LunBoBean.DataBean dataBean : ((LunBoBean) o).getData()) {
                ImageView imageView = new ImageView(context);
                imageView.setImageResource(R.mipmap.news_advert_dot_d);
                int v = (int) context.getResources().getDimension(R.dimen.point_padding);
                imageView.setPadding(v,v,v,v);
                header_linear.addView(imageView);
            }
            adapter = new HeaderViewPagerAdapter(getContext(), ((LunBoBean) o).getData());
            adapter.setOnImageViewClickListener(this);
            header_viewpager.setAdapter(adapter);
            point.post(()->ViewCompat.setTranslationX(point, header_linear.getLeft()));
            handler.obtainMessage(0, 1, 0).sendToTarget();
        }
        else if(o instanceof DetialsBean){
            newsViewAdapter.addAll(((DetialsBean) o).getData());
            stopProgressDialog();
            loading=false;
        }
    }

    @Override
    public void showDataError(Throwable throwable) {
        ToastUtil.showShort("网络请求失败");
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        float value = header_linear.getLeft() + (position - 1 + positionOffset) * point.getWidth();
        value = Math.max(value, header_linear.getLeft());
        value = Math.min(value, header_linear.getRight() - point.getWidth());
        ViewCompat.setTranslationX(point, value);
    }

    @Override
    public void onPageSelected(int position) {
        PagerAdapter adapter = header_viewpager.getAdapter();
        if (position == 0) {
            header_viewpager.setCurrentItem(adapter.getCount() - 2, false);
        } else if (position == adapter.getCount() - 1) {
            header_viewpager.setCurrentItem(1, false);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    int arg1 = msg.arg1;
                    if (arg1 > header_viewpager.getAdapter().getCount() - 2) {
                        arg1 = 1;
                    }
                    header_viewpager.setCurrentItem(arg1, arg1 != 1);
                    Message message = handler.obtainMessage(0, ++arg1, 0);
                    handler.sendMessageDelayed(message, 3000);
                    break;
            }
            return true;
    }

    @Override
    public void onImageClick(LunBoBean.DataBean dataBean) {
        String app_banner_param = dataBean.getExtra_data().getApp_banner_param();
        if (app_banner_param.contains("http")) {
            Bundle bundle = new Bundle();
            bundle.putString("url",app_banner_param);
            bundle.putString("title","最新");
            WebActivity.showAction(getActivity(),bundle);
        }else{
            Bundle bundle = new Bundle();
            bundle.putString("postid",app_banner_param);
            VideoActivity.showAction(getActivity(),bundle);
        }
    }

    @Override
    public void onItemClick(DetialsBean.DataBean dataBean) {
        Bundle bundle = new Bundle();
        bundle.putString("postid",dataBean.getPostid());
        VideoActivity.showAction(getActivity(),bundle);
    }
}
